 //
//  HMTabBar.swift
//  CZBKWB31
//
//  Created by Linkon Y on 16/8/9.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
 
 //声明协议
 protocol HMTabBarDelegate : NSObjectProtocol{
        //声明方法
    func tabBarButtonClick()
 
  }

class HMTabBar: UITabBar {
    
    //声明一个代理
    weak  var HMDegelate:HMTabBarDelegate?
    

   override init(frame: CGRect) {
        super.init(frame: frame)
          setupUI()
    
    }
    //纯代码必须有这两句
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 
    //添加按钮的事件
    func buttonClick(){

   HMDegelate?.tabBarButtonClick()
    
    
    }
    
    
    // MARK: - 设置视图
    
    private func setupUI(){
    
        addSubview(composeButton)
    
    }
    
     // MARK: - 增加约束
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //子控件的宽度
        let childW = self.frame.width * 0.2
        
        var index : CGFloat = 0
    
        //遍历子控件
        for value in self.subviews{
        
            
            //通过字符换转class
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                    //print(value)
            //设置frame
                value.frame.size.width = childW
                value.frame.origin.x = index * childW
            
                index++
                
                //给添加位置预留位置
                if index == 2 {
                    
                    index++
                }
                
            }
           
        }
        
        
        //设置写的按钮的Frame
        composeButton.center.x = self.frame.width * 0.5
        composeButton.center.y = self.frame.height * 0.5

    }
    
     // MARK: - 懒加载控件
    private lazy var composeButton: UIButton = {
    
        let button = UIButton()
        //增加个代理事件
        button.addTarget(self, action: "buttonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        //增加背景图片
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), forState: UIControlState.Selected)

        //增加图片
        
        button.setImage(UIImage(named:"tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), forState: UIControlState.Selected)
    
        button.sizeToFit()
        
        return button
        
        
    }()
    
    
    
}
